//
//  AppDelegate+Update.m
//  BaseProject
//
//  Created by 王盼盼 on 2024/9/11.
//  Copyright © 2024 wangpanpan. All rights reserved.
//

#import "AppDelegate+Update.h"
#import "AppVersionModel.h"
@implementation AppDelegate (Update)
- (void)versionUpdate {
    WK(weakSelf)
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@"3" forKey:@"versionType"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/my/queryApkVersion"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                AppVersionModel *model = [AppVersionModel modelWithDictionary:resultDic];
                model.NewEdition = [resultDic valueForKey:@"newEdition"];
                [weakSelf versioncompare:model];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}
- (void)versioncompare:(AppVersionModel *)versionModel {
    NSString *locationVersion = APP_VERSION;
    NSString *newVersion = versionModel.NewEdition;
    [Utilities setToNSUserDefaults:@"BA_version" value:newVersion];
    NSComparisonResult result = [locationVersion compare:newVersion];
    switch (result) {
        case NSOrderedAscending:
            if (versionModel.isForce) {
                [TT_Alert alert:versionModel.updateContent doneAction:^{
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:versionModel.downloadUrl] options:nil completionHandler:nil];
                }];
            } else {
                [TT_Alert alert:versionModel.updateContent
                 cancleBtnTitle:@"取消"
                   cancleAction:^{}
                   doneBtnTitle:@"去升级"
                     doneAction:^{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:versionModel.downloadUrl]];
                }];
            }
            break;
        case NSOrderedSame:
            
            break;
        case NSOrderedDescending:
            
            break;
        default:
            break;
    }
}
@end
